package cn.jaye.fabric.application;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import cn.jaye.fabric.application.command.BindApiPackageCommand;
import cn.jaye.fabric.common.constant.ExceptionEnum;
import cn.jaye.fabric.common.constant.Global;
import cn.jaye.fabric.common.constant.MicroConstant;
import cn.jaye.fabric.common.exception.ServiceException;
import cn.jaye.fabric.domain.service.RestTemplateService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @author Jaye
 * @create 2018-01-10 9:54
 */
@Service
public class AccessPointApiPackageApplicationService {

    @Autowired
    private RestTemplateService restTemplateService;

    @Autowired
    private MicroConstant microConstant;

    private static final String APIPACKAGR_SERVICE_NAME = "apiauthorize";

    public boolean bindApiPackage(BindApiPackageCommand bindApiPackageCommand) {
//        String url = "http://localhost:/packageToTenant";
        String[] apiPackages = bindApiPackageCommand.getAddApiPackages();
        String url = microConstant.getApiGatewayAddress() + APIPACKAGR_SERVICE_NAME + "/packageToTenant";
        JSONObject postData = new JSONObject();
        postData.put("tenantId", bindApiPackageCommand.getAccessPointId());
        postData.put("serviceStartTime", "2018-01-01 00:00:00");
        postData.put("serviceEndTime", "2020-01-01 00:00:00");
        postData.put("useState", 0);
        int length = apiPackages.length;
        if (length > 0) {
            int failedNum = 0;
            for (int i = 0; i < length; i++) {
                postData.put("apiPackageId", apiPackages[i]);
                try {
                    JSONObject resultObject = restTemplateService.getUrlResponse(url, postData);
                    if (!Global.SUCCESS_FLAG.equals(resultObject.getInteger("code"))) {
                        throw new ServiceException(ExceptionEnum.TENANT_APIPACKAGE_BIND_FAILED);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    failedNum++;
                }
            }
            if (failedNum == length) {
                return false;
            }
            return true;
        }
        return false;
    }

    public String listAccessPointApiPackage() {
        String url = microConstant.getApiGatewayAddress() + APIPACKAGR_SERVICE_NAME + "/tenant/apipackage/list";
        JSONObject postData = new JSONObject();
        JSONObject resultObject = restTemplateService.getUrlResponse(url, postData);
        return JSON.toJSONString(resultObject);
    }
}
